package com.kgc.crowd.ossdemo.controller;

import com.kgc.crowd.ossdemo.utils.AliyunOSSUtil;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * 项目名：distribution-crowd-parent
 * 创建人：Junyizm
 * 创建时间：2020/3/26-11:29
 */
@RestController
public class OSSController {

    @RequestMapping("/toupload")
    public String toupload(){
        return "upload";
    }

    @RequestMapping("/upload")
    public String upload(@RequestParam("projectheadpic")MultipartFile projectheadpic, Model model){
        if(projectheadpic!= null){
            String filename = projectheadpic.getOriginalFilename();
            InputStream inputStream = null;
            try {
                inputStream = projectheadpic.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                String upload = AliyunOSSUtil.upload(inputStream,filename);
                model.addAttribute("ingURL","https://distribution-crowd2.oss-cn-beijing.aliyuncs.com/"+upload);
                model.addAttribute("msg","文件上传成功");
                return "upload";
            }catch (Exception e){
                e.printStackTrace();
                model.addAttribute("msg",e.getMessage());
                return "upload";
            }
        }else{
            model.addAttribute("msg","请选择文件");
            return "upload";
        }
    }
}
